<template>
  <div class='container'>
    <Header breadcrumb='S7F25' title='S7F25' />
    <div class='form'>
      <el-row :gutter='30'>
        <el-col :span='3'>
          <div class='label'>握手等待时间:</div>
        </el-col>
        <el-col :span='5'>
          <el-input placeholder='握手等待时间' v-model='S7F25.shakeHandsWaitTime' clearable></el-input>
        </el-col>
        <el-col :span='13'>
        </el-col>
      </el-row>
      <el-row :gutter='30'>
        <el-col :span='5' offset='3'>
          <div class='label'>变量地址</div>
        </el-col>
        <el-col :span='4'>
          <div class='label'>变量类型</div>
        </el-col>
        <el-col :span='4'>
          <div class='label'>变量名称</div>
        </el-col>
        <el-col :span='2'>
          <div class='label'>变量长度</div>
        </el-col>
        <el-col :span='2'>
          <div class='label'>变量倍率</div>
        </el-col>
        <el-col :span='3'>
        </el-col>
      </el-row>
      <el-row :gutter='30'>
        <el-col :span='3'>
          <div class='label'>握手发送:</div>
        </el-col>
        <el-col :span='5'>
          <el-input placeholder='地址' v-model='S7F25.shakeHandsSend.addr' clearable></el-input>
        </el-col>
        <el-col :span='4'>
          <el-select v-model='S7F25.shakeHandsSend.type'>
            <el-option v-for='(value, name) in plcTypeOptions' :key='value' :value='name' :label='value'></el-option>
          </el-select>
        </el-col>
        <el-col :span='4'>
          <el-input placeholder='名称' v-model='S7F25.shakeHandsSend.name' clearable>
          </el-input>
        </el-col>
        <el-col :span='2'>
          <el-input placeholder='变量长度' v-model='S7F25.shakeHandsSend.len' clearable>
          </el-input>
        </el-col>
        <el-col :span='2'>
          <el-input placeholder='倍率' v-model='S7F25.shakeHandsSend.factor' clearable>
          </el-input>
        </el-col>
        <el-col :span='2'>
        </el-col>
      </el-row>
      <el-row :gutter='30'>
        <el-col :span='3'>
          <div class='label'>握手接收:</div>
        </el-col>
        <el-col :span='5'>
          <el-input placeholder='地址' v-model='S7F25.shakeHandsRev.addr' clearable></el-input>
        </el-col>
        <el-col :span='4'>
          <el-select v-model='S7F25.shakeHandsRev.type'>
            <el-option v-for='(value, name) in plcTypeOptions' :key='value' :value='name' :label='value'></el-option>
          </el-select>
        </el-col>
        <el-col :span='4'>
          <el-input placeholder='名称' v-model='S7F25.shakeHandsRev.name' clearable>
          </el-input>
        </el-col>
        <el-col :span='2'>
          <el-input placeholder='变量长度' v-model='S7F25.shakeHandsRev.len' clearable>
          </el-input>
        </el-col>
        <el-col :span='2'>
          <el-input placeholder='倍率' v-model='S7F25.shakeHandsRev.factor' clearable>
          </el-input>
        </el-col>
        <el-col :span='3'>
        </el-col>
      </el-row>
      <el-row :gutter='30'>
        <el-col :span='3'>
          <div class='label'>PPID:</div>
        </el-col>
        <el-col :span='5'>
          <el-input placeholder='地址' v-model='S7F25.ppid.addr' clearable></el-input>
        </el-col>
        <el-col :span='4'>
          <el-select v-model='S7F25.ppid.type'>
            <el-option v-for='(value, name) in plcTypeOptions' :key='value' :value='name' :label='value'></el-option>
          </el-select>
        </el-col>
        <el-col :span='4'>
          <el-input placeholder='名称' v-model='S7F25.ppid.name' clearable>
          </el-input>
        </el-col>
        <el-col :span='2'>
          <el-input placeholder='变量长度' v-model='S7F25.ppid.len' clearable>
          </el-input>
        </el-col>
        <el-col :span='2'>
          <el-input placeholder='倍率' v-model='S7F25.ppid.factor' clearable>
          </el-input>
        </el-col>
        <el-col :span='3'>
        </el-col>
      </el-row>
      <el-row :gutter='20'>
        <el-col :span='3' offset='2'>
          <div class='grid-content bg-purple'>
            <el-button type='primary' size='small' icon='el-icon-check' :loading='loading' @click='submit'>保存
            </el-button>
          </div>
        </el-col>
        <el-col :span='3'>
          <div class='grid-content bg-purple'>
            <el-button type='primary' size='small' icon='el-icon-check' :loading='loading' @click='refresh'>刷新
            </el-button>
          </div>
        </el-col>
        <el-col :span='3'>
          <div class='grid-content bg-purple'>
            <el-button type='primary' size='small' icon='el-icon-check' :loading='loading' @click='addStep'>插入Step
            </el-button>
          </div>
        </el-col>
        <el-col :span='3'>
          <div class='grid-content bg-purple'>
            <el-button type='primary' size='small' icon='el-icon-check' :loading='loading' @click='addStepAuto'>
              插入Step_Auto
            </el-button>
          </div>
        </el-col>
        <el-col :span='3'>
          <div class='grid-content bg-purple'>
            <el-button type='primary' icon='el-icon-receiving' size='small' :loading='loading'
                       :disabled='checking|| improtUrlDisabled' @click='selectFile($event)'>导入
            </el-button>
            <input type='file' name='' id='uploadEventFile' style='display:none' @change='importS7F25Conf($event)'
                   accept='.json, application/json, text/json'>
          </div>
        </el-col>
        <el-col :span='3'>
          <div class='grid-content bg-purple'>
            <el-button type='primary' icon='el-icon-paperclip' size='small' :loading='loading'
                       :disabled='checking|| exportUrlDisabled' @click='exportS7F25Conf'>导出
            </el-button>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter='10'>
        <el-col :span='2' class='label'>Steps:</el-col>
        <el-col :span='22'>
        </el-col>
      </el-row>
      <el-collapse>
        <el-collapse-item v-bind:title="'Step_' +(index+1)" v-bind:name='index' v-for='(step,index) in S7F25.steps'
                          :key='index'>
          <el-row :gutter='10'>
            <el-col :span='7' offset='1'>
              <el-input placeholder='地址' v-model='step.stepPlcItem.addr' clearable>
              </el-input>
            </el-col>
            <el-col :span='3'>
              <el-select v-model='step.stepPlcItem.type'>
                <el-option v-for='(value, name) in plcTypeOptions' :key='value' :value='name'
                           :label='value'></el-option>
              </el-select>
            </el-col>
            <el-col :span='4'>
              <el-input placeholder='名称' v-model='step.stepPlcItem.name' clearable>
              </el-input>
            </el-col>
            <el-col :span='2'>
              <el-input placeholder='变量长度' v-model='step.stepPlcItem.len' clearable>
              </el-input>
            </el-col>
            <el-col :span='2'>
              <el-input placeholder='倍率' v-model='step.stepPlcItem.factor' clearable>
              </el-input>
            </el-col>
            <el-button type='danger' icon='el-icon-delete' @click='delStep(index)' :span='2'>删除</el-button>
            <el-col :span='1' v-if='index==0'>
              <el-input placeholder='偏移量' v-model='stepOffset'></el-input>
            </el-col>
            <el-col :span='3'>
            </el-col>
          </el-row>

          <el-row :gutter='10'>
            <el-col :span='2'>Recipe List:</el-col>
            <el-col :span='2'>
              <el-button type='primary' size='small' icon='el-icon-check' :loading='loading'
                         @click='addStepItem(index)'>插入Recipe
              </el-button>
            </el-col>
          </el-row>

          <el-row :gutter='10' v-for='(stepItem,itemIndex) in step.stepItems' :key='itemIndex'>
            <el-col :span='7' offset='1'>
              <el-input placeholder='地址' v-model='stepItem.addr' clearable>
              </el-input>
            </el-col>
            <el-col :span='3'>
              <el-select v-model='stepItem.type'>
                <el-option v-for='(value, name) in plcTypeOptions' :key='value' :value='name'
                           :label='value'></el-option>
              </el-select>
            </el-col>
            <el-col :span='4'>
              <el-input placeholder='名称' v-model='stepItem.name' clearable>
              </el-input>
            </el-col>
            <el-col :span='2'>
              <el-input placeholder='变量长度' v-model='stepItem.len' clearable>
              </el-input>
            </el-col>
            <el-col :span='2'>
              <el-input placeholder='倍率' v-model='stepItem.factor' clearable>
              </el-input>
            </el-col>
            <el-col :span='1' v-if='index==0'>
              <el-input placeholder='偏移量' v-model='offset[itemIndex]'></el-input>
            </el-col>
            <el-button type='danger' icon='el-icon-delete' circle @click='delStepItem(index,itemIndex)'
                       :span='2'></el-button>
            <el-col :span='5'>
            </el-col>
          </el-row>

        </el-collapse-item>
      </el-collapse>

    </div>
  </div>
</template>

<script>
import {
  exportS7F25Conf, getS7F25Info, importS7F25Conf, setS7F25Info,
} from '@/api/request';
import Header from './common/Header.vue';

export default {
  name: 'S7F25',
  data() {
    return {
      plcTypeOptions: this.$store.state.plcTypeOptions || {},
      loading: false,
      stepOffset: 5,
      offset: [1, 1, 1, 1],
      S7F25: {
        shakeHandsSend: {
          addr: '',
          addrHead: '',
          addrNum: 0,
          addrCnt: 0,
          type: '',
          name: '',
          len: '',
          factor: 1.0,
        },
        shakeHandsRev: {
          addr: '',
          addrHead: '',
          addrNum: '',
          addrCnt: 0,
          type: '',
          name: '',
          len: '',
          factor: 1.0,
        },
        shakeHandsWaitTime: 4000,
        ppid: {
          addr: '',
          addrHead: '',
          addrNum: '',
          addrCnt: 0,
          type: '',
          name: '',
          len: '',
          factor: 1.0,
        },
        steps: [
          {
            stepPlcItem: {
              addr: '1',
              addrHead: '',
              addrNum: '',
              addrCnt: 0,
              type: '',
              name: '',
              len: '',
              factor: 1.0,
            },
            stepItems: [
              {
                addr: '',
                addrHead: '',
                addrNum: '',
                addrCnt: 0,
                type: '',
                name: '',
                len: '',
                factor: 1.0,
              },
            ],
          },
        ],
      },
    };
  },
  components: {
    Header,
  },
  created() {
    this.getS7F25Info3();
  },
  methods: {
    getS7F25Info3() {
      getS7F25Info()
        .then((res) => {
          if (res) {
            this.S7F25 = res;
          }
        });
    },
    submit() {
      setS7F25Info(this.S7F25)
        .then((res) => {
          if (res && res.status === 200) {
            this.$message({
              message: res.msg || '保存设置成功',
              type: 'success',
            });
          }
        });
    },
    refresh() {
      getS7F25Info()
        .then((res) => {
          if (res) {
            this.S7F25 = res;
          }
        });
    },
    addStep() {
      const { steps } = this.S7F25;
      const stepsLastIndex = steps.length - 1;
      if (stepsLastIndex >= 0) {
        // eslint-disable-next-line no-unused-vars
        const stepLast = steps[stepsLastIndex];
        // eslint-disable-next-line no-unused-vars
        const stepLastNew = {
          stepPlcItem: {
            addr: stepLast.stepPlcItem.addr,
            addrHead: stepLast.stepPlcItem.addrHead,
            addrNum: stepLast.stepPlcItem.addrNum,
            addrCnt: stepLast.stepPlcItem.addrCnt,
            type: stepLast.stepPlcItem.type,
            name: stepLast.stepPlcItem.name,
            len: stepLast.stepPlcItem.len,
            factor: 1.0,
          },
          stepItems: [],
        };
        // eslint-disable-next-line no-plusplus
        for (let i = 0; i < stepLast.stepItems.length; i++) {
          stepLastNew.stepItems.push(
            {
              addr: stepLast.stepItems[i].addr,
              addrHead: stepLast.stepItems[i].addrHead,
              addrNum: stepLast.stepItems[i].addrNum,
              addrCnt: stepLast.stepItems[i].addrCnt,
              type: stepLast.stepItems[i].type,
              name: stepLast.stepItems[i].name,
              len: stepLast.stepItems[i].len,
              factor: 1.0,
            },
          );
        }
        steps.push(
          // eslint-disable-next-line no-undef
          stepLastNew,
        );
      } else {
        this.S7F25.steps.push({
          stepPlcItem: {
            addr: '',
            addrHead: '',
            addrNum: '',
            addrCnt: 0,
            type: '',
            name: '',
            len: '',
            factor: 1.0,
          },
          stepItems: [
            {
              addr: '',
              addrHead: '',
              addrNum: '',
              addrCnt: 0,
              type: '',
              name: '',
              len: '',
              factor: 1.0,
            },
          ],
        });
      }
    },
    addStepAuto() {
      const addCntMap = this.offset;
      const { stepOffset } = this;
      const { steps } = this.S7F25;
      const stepsLastIndex = steps.length - 1;
      if (stepsLastIndex >= 0) {
        // eslint-disable-next-line no-unused-vars
        const stepLast = steps[stepsLastIndex];// 获取最后一步的所有信息
        // const preAddr = stepLast.stepPlcItem.addr.substring(1, stepLast.stepPlcItem.addr.length);
        // const preHead = stepLast.stepPlcItem.addr.substring(0, 1);
        // const addr1 = preHead + (Number(preAddr) + Number(stepOffset));
        // eslint-disable-next-line no-undef
        let pattern = /\d/;
        const firstNumberIndex = pattern.exec(stepLast.stepPlcItem.addr).index;
        // eslint-disable-next-line no-undef
        pattern = /\d(?=[^\d]*$)/;
        const lastNumberIndex = pattern.exec(stepLast.stepPlcItem.addr).index;
        const first = stepLast.stepPlcItem.addr.substring(0, firstNumberIndex);
        let second = stepLast.stepPlcItem.addr.substring(firstNumberIndex, lastNumberIndex + 1);
        const third = stepLast.stepPlcItem.addr.substring(lastNumberIndex + 1, stepLast.stepPlcItem.addr.length) != null ? stepLast.stepPlcItem.addr.substring(lastNumberIndex + 1, stepLast.stepPlcItem.addr.length) : '';
        second = Number(second) + Number(stepOffset);
        const StepNameStr = `Step${this.S7F25.steps.length + 1}`;
        const stepLastNew = {
          stepPlcItem: {
            addr: first + second + third,
            addrHead: stepLast.stepPlcItem.addrHead,
            addrNum: stepLast.stepPlcItem.addrNum,
            addrCnt: stepLast.stepPlcItem.addrCnt,
            type: stepLast.stepPlcItem.type,
            name: StepNameStr,
            len: stepLast.stepPlcItem.len,
            factor: 1.0,
          },
          stepItems: [],
        };
        // eslint-disable-next-line no-undef
        // eslint-disable-next-line no-plusplus
        for (let i = 0; i < stepLast.stepItems.length; i++) {
          pattern = /\d/;
          // eslint-disable-next-line no-undef
          const firstNumberIndex2 = pattern.exec(stepLast.stepItems[i].addr).index;
          pattern = /\d(?=[^\d]*$)/;
          // eslint-disable-next-line no-undef
          const lastNumberIndex2 = pattern.exec(stepLast.stepItems[i].addr).index;
          // eslint-disable-next-line no-unused-vars
          const first2 = stepLast.stepItems[i].addr.substring(0, firstNumberIndex2);
          let second2 = stepLast.stepItems[i].addr.substring(firstNumberIndex2, lastNumberIndex2 + 1);
          let third2 = stepLast.stepItems[i].addr.substring(lastNumberIndex2 + 1, stepLast.stepPlcItem.addr.length);
          second2 = Number(second2) + Number(addCntMap[i]);
          third2 = third2 != null ? third2 : '';
          stepLastNew.stepItems.push(
            {
              addr: first2 + second2 + third2,
              addrHead: stepLast.stepItems[i].addrHead,
              addrNum: stepLast.stepItems[i].addrNum,
              addrCnt: stepLast.stepItems[i].addrCnt,
              type: stepLast.stepItems[i].type,
              name: stepLast.stepItems[1].name,
              len: stepLast.stepItems[i].len,
              factor: 1.0,
            },
          );
        }
        steps.push(
          // eslint-disable-next-line no-undef
          stepLastNew,
        );
      } else {
        this.S7F25.steps.push({
          stepPlcItem: {
            addr: '',
            addrHead: '',
            addrNum: '',
            addrCnt: 0,
            type: '',
            name: '',
            len: '',
            factor: 1.0,
          },
          stepItems: [
            {
              addr: '',
              addrHead: '',
              addrNum: '',
              addrCnt: 0,
              type: '',
              name: '',
              len: '',
              factor: 1.0,
            },
          ],
        });
      }
    },
    addStepItem(index) {
      const { stepItems } = this.S7F25.steps[index];
      const stepItemLastIndex = stepItems.length - 1;
      if (stepItemLastIndex >= 0) {
        const stepItemLast = stepItems[stepItemLastIndex];
        stepItems.push({
          addr: '',
          addrHead: stepItemLast.addrHead,
          addrNum: stepItemLast.addrNum,
          addrCnt: stepItemLast.addrCnt,
          type: stepItemLast.type,
          name: stepItemLast.name,
          len: stepItemLast.len,
          factor: stepItemLast.factor,
        });
      } else {
        this.S7F25.steps[index].stepItems.push({
          addr: '',
          addrHead: '',
          addrNum: '',
          addrCnt: 0,
          type: '',
          name: '',
          len: '',
          factor: 1.0,
        });
      }
    },
    delStep(index) {
      this.S7F25.steps.splice(index, 1);
    },
    delStepItem(index, itemIndex) {
      this.S7F25.steps[index].stepItems.splice(itemIndex, 1);
    },
    importS7F25Conf(event) {
      this.$parent.loading = true;
      const file = event.target.files[0];
      importS7F25Conf(file)
        .then((res) => {
          console.log('res:', res);
          this.$message({
            message: res.msg,
            type: res.status === 200 ? 'success' : 'error',
          });
          // 刷新父组件数据
          if (res.status === 200) {
            this.refresh();
          }
        })
        .catch((error) => {
          this.$message.error(error.message || '发生了网络错误');
        })
        .finally(() => {
          this.$parent.loading = false;
        });
    },
    exportS7F25Conf() {
      exportS7F25Conf()
        .then((res) => {
          if (res && res.data) {
            const { data } = res;
            const result = JSON.stringify(data, null, 2);
            console.log(result);
            const blob = new Blob([result], {
              type: 'text/json;charset=utf-8;',
            });
            const filename = res.fileName || '导出数据';
            if (navigator.msSaveBlob) {
              // IE 10+
              navigator.msSaveBlob(blob, filename);
            } else {
              const link = document.createElement('a');
              if (link.download !== undefined) {
                // feature detection
                const url = URL.createObjectURL(blob);
                link.setAttribute('href', url);
                link.setAttribute('download', filename);
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
              }
            }
            this.$message({
              message: '导出数据成功',
              type: 'success',
            });
          }
        });
      this.exportVisible = false;
    },
    selectFile(event) {
      event.preventDefault();
      document.querySelector('#uploadEventFile')
        .click();
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang='scss'>
.container {
  .el-row {
    margin-bottom: 20px;
  }

  .form {
    margin: 1rem;
    display: flex;
    flex-direction: column;

    .item {
      margin-bottom: 1rem;
      display: flex;
      align-items: center;
      width: 50%;

      label {
        width: auto;
        text-align: right;
        padding-right: 1rem;
      }

      .label-left {
        width: 200px;
        text-align: left;
        padding-right: 1rem;
      }

      .input-left {
        float: left;
      }

      .el-input,
      .el-select {
        width: 300px;
      }
    }

    .buttons {
      margin-top: 2rem;
      display: flex;
      justify-content: space-around;
    }
  }
}
</style>
